﻿using System;
using System.Web.Mvc;
using Shell.DomainDot;
using Framework.Domain;
using Framework.Mvc.ViewModels;
using System.Web.Security;

namespace Framework.Mvc.Controllers
{
    /// <summary>
    /// 管理员登陆
    /// </summary>
    public class HomeController : Controller
    {
        private IDomainDotFactory factory;

        /// <summary>
        /// 构造器
        /// </summary>
        public HomeController()
        {
            factory = DomainDotFactory.Factory;
        }

        /// <summary>
        /// 管理员登陆
        /// </summary>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 管理员登陆
        /// </summary>
        [HttpPost]
        public ActionResult Index(LogOnViewModel model)
        {
            var verifyCode = Session["LogOnVerifyCode"].ToString();
            if (!String.IsNullOrEmpty(verifyCode) && verifyCode.Equals(model.VerfityCode, StringComparison.CurrentCultureIgnoreCase))
            {
                var context = factory.Create<UserRegisterContext>();
                var user = context.FindNameUser(model.Name);
                if (user != null && user.IsAdmin)
                {
                    var hashedPassword = EncryptionHelper.Md5Hash(model.Password);
                    if (hashedPassword.Equals(user.Password, StringComparison.CurrentCulture))
                    {
                        FormsAuthentication.SetAuthCookie(user.Name, false);
                        return this.RedirectToAction("List", "AgencyManager");
                    }
                }
            }
            return View();
        }

        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();
            return this.RedirectToAction("Index");
        }
    }
}